package com.albaba.springalibabasentinel8085.controller;

import com.albaba.springalibabasentinel8085.service.SentinelService;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author zx
 * @version 1.0
 * @description TODO
 * @date 2024/11/18 21:35
 */

@RestController
@Slf4j
public class SentinelController {

    @Resource
    private SentinelService sentinelService;

    @GetMapping("/a")
    @SentinelResource(value = "a")
    public String a() {
        return "a";
    }

    @GetMapping("/b")
    public String b() {
        return "b";
    }

    @GetMapping("/testA")
    public String testA() {
        log.info("testA");
        return sentinelService.testA();
    }

    @GetMapping("/testB")
    public String testB() {
        return sentinelService.testB();
    }

    @GetMapping("/testC")
    public String testC() {

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        return "testC";
    }

    @GetMapping("/testD")
    public String testD(Integer id) {
        if (id > 1) {
            throw new RuntimeException("id>1");
        }
        return "testD";
    }

    @GetMapping("/testHotKey")
    @SentinelResource(value = "testHotKey", blockHandler = "handler_hotKey")
    public String testHotKey(@RequestParam(value = "hot1", required = false) String hot1,
                             @RequestParam(value = "hot2", required = false) String hot2,
                             @RequestParam(value = "hot3", required = false) String hot3) {

        if ("6".equals(hot1)){
            throw new RuntimeException();
        }

        return "testE";
    }

    public String handler_hotKey(String hot1, String hot2, String hot3, BlockException e) {
        return "系统繁忙请稍后重试!";
    }
}
